package com.youdianda.aspect;


import com.youdianda.annotation.AutoFill;
import com.youdianda.constant.AutoFillConstant;
import com.youdianda.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

/**
 * 自动填充切面类
 */
@Slf4j
@Aspect
@Component
public class AutoFillAspect {

    @Pointcut("execution(* com.youdianda.mapper.*.*(..))")
    public void mapper() {}

    @Before("mapper() && @annotation(com.youdianda.annotation.AutoFill)")
    public void autoFill(JoinPoint joinPoint) {
        log.info("开始自动填充");
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();

        AutoFill autoFill = signature.getMethod().getAnnotation(AutoFill.class);

        Object[] args = joinPoint.getArgs();

        if (args == null || args.length <= 0) {
            return;
        }

        Object entity = args[0];

        LocalDateTime nowTime = LocalDateTime.now();

        OperationType operationType = autoFill.value();

        try {
            if (operationType == OperationType.INSERT) {

                Method setCreateTime = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);
                Method setUpdateTime = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);

                setCreateTime.invoke(entity, nowTime);
                setUpdateTime.invoke(entity, nowTime);
            } else if (operationType == OperationType.UPDATE){

                Method setUpdateTime = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);

                setUpdateTime.invoke(entity, nowTime);
            }
            Method setDefaultData = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_DEFAULT_DATA, String.class);

            setDefaultData.invoke(entity, "1");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }
}
